<?php

class ImgsController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/simple';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
//			'deleteOwn + delete', // we only allow deletion via POST request
//            'updateOwn + update', // Apply this filter only for the update action.
//            'rights',
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('create','index','view','getTime','ajax_google_code','ajax_google_data','ajax_google_allshop','Ajax_google_data_v20130124'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('update','get_google_code','list_imgs','list_post','list_imei','list_place'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	public function actionGetTime()
	{
	
		
	}
	
	public function actionGet_google_code()
	{
		if(!Yii::app()->request->isPostRequest)
		{
			$model = new Imgs;
			$this->render('searchtime',array(
					'model'=>$model,
			));
		}else{
            $model = new Imgs;
			$ctime = $_POST['ctime'];
            $utime = $_POST['utime'];
            $uid = $_POST['Imgs']['uid'];
            $speed = $_POST['Imgs']['order'];

            $model->ctime = $ctime;
            $model->utime = $utime;
            $model->uid = $uid;
            $model->order = $speed;

//			$this->layout = '//layouts/column1';
			$this->render('map2',array(
                'utime'=>$utime,
                'ctime'=>$ctime,
                'uid'=>$uid,
                'speed'=>$speed,
                'model'=>$model
//                'time1'=>$_POST['time1'],
//                'time2'=>$_POST['time2']
//                'h1'=>$_POST['h1'],
//                'h2'=>$_POST['h2'],
//                'm1'=>$_POST['m1'],
//                'm2'=>$_POST['m2'],
//                's1'=>$_POST['s1'],
//                's2'=>$_POST['s2'],
            ));
		}
	
	}


	
	public function actionAjax_google_code()
	{
//		$time = $_GET['time'];
//		$user_id = Yii::app()->user->id;
        $user_id = Yii::app()->request->getParam('uid', 0);
        $time = Yii::app()->request->getParam('time', time());  //默认当前时间

		if($user_id!='')
		{
			$sql = "select * from blog_imgs where uid = ".$user_id." and FROM_UNIXTIME(ctime, '%Y-%m-%d') = '$time'";
			//echo $sql;
			/*$points = Imgs::model()->findAllByAttributes(
					array('uid' => $user_id)
			);*/
			$points = Imgs::model()->findAllBysql($sql);

			if(count($points)!=0)
			{
				$criteria=new CDbCriteria;
				$criteria->select='latitude'; // only select the ’title’ column
				$criteria->addCondition("uid=$user_id");
				
				$count=Imgs::model()->count($criteria);
				
				
				foreach ($points as $key=>$values){
					if($values['latitude']!=''&& $values['longitude']!='')
					{
						$newpoints[$key] = $values;
					}
				}
				
				$count = count($newpoints);
				$mid = intval(round($count/2,0));
				foreach($newpoints as $key=>$values){
					if($key==0){
						$outstart = array('location'=>$values['latitude'].','.$values['longitude']);
					}
					if($key==$mid)
					{
						$outmid = array('latitude'=>$values['latitude'],'longitude'=>$values['longitude']);
					}
					//$out[]= '{location:"'.$values['longitude'].','.$values['longitude'].'",stopover:true},';
					$out[]=array('location'=>$values['latitude'].','.$values['longitude'],'stopover'=>true,'time'=>$values['ctime']);
					$out1[] = array('latitude'=>$values['latitude'],'longitude'=>$values['longitude'],'content'=>$values['content']);
					if($key==$count-1){
						$outend = array('location'=>$values['latitude'].','.$values['longitude']);
					}
				}

                $out1_new = array();
                if(!empty($out1)){
//                    $c_out = count($out);
                    $out1_tmp = array();
                    foreach($out1 as $out1_one){
                        if(empty($out1_tmp)){
                            $out1_tmp = $out1[0];
                            $out1_new[]=array('location'=>$out1[0]['latitude'].','.$out1[0]['longitude'],'stopover'=>true);
                        }
                        if(($out1_one['time']-$out1_tmp['time'])>1800){
                            $out1_tmp = $out1_one;
                            $out1_new[]=array('location'=>$out1_tmp['latitude'].','.$out1_tmp['longitude'],'content'=>$out1_tmp['content']);
                        }
                    }
                }

                //轨迹最少间隔为两小时
                $out_new = array();
                if(!empty($out)){
//                    $c_out = count($out);
                    $out_tmp = array();
                    foreach($out as $out_one){
                        if(empty($out_tmp)){
                            $out_tmp = $out[0];
                            $out_new[]=array('location'=>$out[0]['latitude'].','.$out[0]['longitude'],'stopover'=>true);
                        }
                        if(($out_one['time']-$out_tmp['time'])>3600*2){
                            $out_tmp = $out_one;
                            $out_new[]=array('location'=>$out_tmp['latitude'].','.$out_tmp['longitude'],'stopover'=>true);
                        }
                    }
                }

				echo json_encode(array('out'=>$out_new,'out1'=>$out1_new,'outmid'=>$outmid,'outstart'=>$outstart,'outend'=>$outend));
			}
			
			/*
            $out[]=array('location'=>'39.961497,116.284018','stopover'=>true);
            $out[]=array('location'=>'39.966464,116.283417','stopover'=>true);
            $out[]=array('location'=>'39.966925,116.28861','stopover'=>true);
            $out[]=array('location'=>'39.966464,116.283417','stopover'=>true);
            $out[]=array('location'=>'39.961497,116.284018','stopover'=>true);
           /* $out[]='location:"39.961497,116.284018",stopover:true';
           $out[]='location:"39.966464,116.283417",stopover:true';
            $out[]='location:"39.966925,116.28861",stopover:true';
           $out[]='location:"39.966464,116.283417",stopover:true';
           $out[]='location:"39.961497,116.284018",stopover:true';
           */
          



           /* $p = '[{"location":"39.961497,116.284018","stopover":true},'.
                '{"location":"39.966464,116.283417","stopover":true},'.
                '{"location":"39.966925,116.28861","stopover":true},'.
                '{"location":"39.966464,116.283417","stopover":true},'.
                '{"location":"39.961497,116.284018","stopover":true}]';*/

          //  echo $p;
		}		
		
		
	}

    //改进算法，去重复点
    public function actionAjax_google_data()
    {     
//        $time = $_GET['time'];
//        $user_id = Yii::app()->user->id;

        $user_id = Yii::app()->request->getParam('uid', 0);
        $time = Yii::app()->request->getParam('time', time());  //默认当前时间
        if($user_id!='')
        {
            $sql = "select * from blog_imgs where uid = ".$user_id." and FROM_UNIXTIME(ctime, '%Y-%m-%d') = '$time'";
            $points = Imgs::model()->findAllBysql($sql);
            if(count($points)!=0)
            {
                $criteria=new CDbCriteria;
                $criteria->select='latitude'; // only select the ’title’ column
                $criteria->addCondition("uid=$user_id");

                $count=Imgs::model()->count($criteria);
                $mid = intval(round($count/2,0));

                $last = '';
                $content = '';
                $m = 0;
                foreach ($points as $key=>$values){
//                    pr("=================");pr("\r\n");

                    if(empty($values['latitude']) || empty($values['longitude']))
                    {
                        continue;
                    }

                    if(!empty($last)){
                        $ds = $this->get_point_distance($values['latitude'], $values['longitude'], $last['latitude'], $last['longitude']);
                        $content .= !empty($values['content']) ? $values['content'].'<br />' : '';
                        $content .= !empty($values['img']) ? '<img src="'.$values['img'].'" />' : '';

                        if($ds > 0.0004){
                            $out[$m]=array('location'=>$values['latitude'].','.$values['longitude'],'stopover'=>true);
                            $out1[$m] = array('latitude'=>$values['latitude'],'longitude'=>$values['longitude'],'content'=>$content);

                            $last = $values;
                            $content = '';
                            $m++;
                        }else{
                            $out[$m]=array('location'=>$last['latitude'].','.$last['longitude'],'stopover'=>true);
                            $out1[$m] = array('latitude'=>$last['latitude'],'longitude'=>$last['longitude'],'content'=>$content);

                            $last = $last;
                        }
                    }else{
                        $last=$values;
                    }


                    if($m==0){
                        $outstart = array('location'=>$values['latitude'].','.$values['longitude']);
                        $outmid = array('latitude'=>$values['latitude'],'longitude'=>$values['longitude']);
                    }

                    $outend = array('location'=>$values['latitude'].','.$values['longitude']);


//                    echo 'out:';if(isset($out))pr($out);pr("\r\n");
//                    echo 'out1:';if(isset($out1))pr($out1);pr("\r\n");
//                    echo 'outmid:';if(isset($outmid))pr($outmid);pr("\r\n");
//                    echo 'outstart:';if(isset($outstart))pr($outstart);pr("\r\n");
//                    echo 'outend:';if(isset($outend))pr($outend);pr("\r\n");
//                    pr("=================");pr("\r\n");pr("\r\n");

                }


                echo json_encode(array('out'=>$out,'out1'=>$out1,'outmid'=>$outmid,'outstart'=>$outstart,'outend'=>$outend));
            }
        }


    }

    public function actiongoogle_allshop()
    {
    	
    	$this->render('mapshop',array(
    	));
    	
    	
    }
    public function actionAjax_google_allshop()
    {

    		$sql = "select * from blog_shop ";
    		$shop = Imgs::model()->findAllBysql($sql);
            $outshop = array();
    		if(count($shop)!=0)
    		{
    			foreach ($shop as $key=>$values)
    			{
    				$content = '';
    				if(empty($values['latitude']) || empty($values['longitude']))
    				{
    					continue;
    				}
                    $content .= !empty($values['title']) ? $values['title'].'<br />' : '';
    				$content .= !empty($values['content']) ? '<div style="font-size:12px;border: 1px solid #CCCCCC;">'.$values['content'].'</div><br />' : '';
    				$content .= !empty($values['img']) ? '<img width="200" src="'.$values['img'].'" />' : '';
    				$outshop[] = array('latitude'=>$values['latitude'],'longitude'=>$values['longitude'],'content'=>$content,'type'=>(($values->enabled==0) ? '1' : '') . $values['type']);
    			}
    		}  		
    	
    	echo json_encode(array('outshop'=>$outshop));  	
    }
    
    
    
    public function actionAjax_google_data_v20130124()
    {
        $user_id = Yii::app()->request->getParam('uid', 0);
        $ctime = Yii::app()->request->getParam('ctime', '');  //默认当前时间
        $utime = Yii::app()->request->getParam('utime', '');  //默认当前时间
        $speed = Yii::app()->request->getParam('speed', 200);

//        $h1 = Yii::app()->request->getParam('h1', 0);
//        $h2 = Yii::app()->request->getParam('h2', 0);
//        $m1 = Yii::app()->request->getParam('m1', 0);
//        $m2 = Yii::app()->request->getParam('m2', 0);
//        $s1 = Yii::app()->request->getParam('s1', 0);
//        $s2 = Yii::app()->request->getParam('s2', 0);
        
        if(empty($ctime)){
            $ctime = date("Y-m-d H:i:s");
        }
        if(empty($utime)){
            $utime = date("Y-m-d H:i:s");
        }

        $ctime_unix = time();
        $utime_unix = time();

        $cut_ctime = explode(' ',$ctime);
        $cut_utime = explode(' ',$utime);
        if(isset($cut_ctime[0]) && isset($cut_ctime[1])){
            $f_ctime = explode('-', $cut_ctime[0]);
            $l_ctime = explode(':', $cut_ctime[1]);
        }
        if(isset($cut_utime[0]) && isset($cut_utime[1])){
            $f_utime = explode('-', $cut_utime[0]);
            $l_utime = explode(':', $cut_utime[1]);
        }

        if(isset($l_ctime[0]) && isset($l_ctime[1]) && isset($l_ctime[2]) && isset($f_ctime[0]) && isset($f_ctime[1]) && isset($f_ctime[2])){
            $ctime_unix = mktime($l_ctime[0], $l_ctime[1],$l_ctime[2], $f_ctime[1], $f_ctime[2], $f_ctime[0]);
        }

        if(isset($l_utime[0]) && isset($l_utime[1]) && isset($l_utime[2]) && isset($f_utime[0]) && isset($f_utime[1]) && isset($f_utime[2])){
            $utime_unix = mktime($l_utime[0], $l_utime[1],$l_utime[2], $f_utime[1], $f_utime[2], $f_utime[0]);
        }


        if($user_id!='')
        {
//            $sql = "select * from blog_imgs where uid = ".$user_id." and FROM_UNIXTIME(ctime, '%Y-%m-%d') >= '$ctime' and FROM_UNIXTIME(ctime, '%Y-%m-%d') <= '$utime'";
            $sql = "select * from blog_imgs where uid = ".$user_id." and ctime >= '$ctime_unix' and ctime <= '$utime_unix' order by aid ASC";
            $points = Imgs::model()->findAllBysql($sql);
            $sql = "select * from blog_shop ";
            $shop = Imgs::model()->findAllBysql($sql);
            if(count($shop)!=0)
            {
            	foreach ($shop as $key=>$values)
            		{
            			$content = '';
            	if(empty($values['latitude']) || empty($values['longitude']))
            	{
            		continue;
            	}
                $content .= !empty($values['title']) ? $values['title'].'<br />' : '';
                $content .= !empty($values['content']) ? '<div style="font-size:12px;border: 1px solid #CCCCCC;">'.$values['content'].'</div><br />' : '';
            	$content .= !empty($values['img']) ? '<img width="200" src="'.$values['img'].'" />' : '';
            	$outshop[] = array('latitude'=>$values['latitude'],'longitude'=>$values['longitude'],'content'=>$content,'type'=>(($values->enabled==0) ? '1' : '') . $values['type']);
            		}
            }
            
            
            if(count($points)!=0)
            {
                $criteria=new CDbCriteria;
                $criteria->select='latitude'; // only select the ’title’ column
                $criteria->addCondition("uid=$user_id");

                $count=Imgs::model()->count($criteria);
                $mid = intval(round($count/2,0));

                $last = '';
                $last2 = '';
                $content = '';
                $m = 0;
                $m2 = 0;
                $out2= array();
                foreach ($points as $key=>$values){

                    if(empty($values['latitude']) || empty($values['longitude']) || $values['latitude']<0 || $values['longitude']<0)
                    {
                        continue;
                    }

                    if(!empty($last)){
                        $ds = $this->get_point_distance($values['latitude'], $values['longitude'], $last['latitude'], $last['longitude']);
//                        pr('['.$m.']');echo "\r\n";
//                        pr($ds);echo "\r\n";
//                        $content .= date("Y-m-d H:i:s", $values['ctime']).'<br />';
                        $content .= !empty($values['title']) ? $values['title'].'<br />' : '';
                        $content .= !empty($values['content']) ? $values['content'].'<br />' : '';
                        $content .= !empty($values['img']) ? '<img width="150" src="'.$values['img'].'" /><br />' : '';

                        if($ds > 0.004){
                            $out[$m]=array('location'=>$last['latitude'].','.$last['longitude'],'stopover'=>true,'time'=>$last['ctime']);
//                            $out1[$m] = array('latitude'=>$values['latitude'],'longitude'=>$values['longitude'],'content'=>$content);

                            $last = $values;
                            $content = '';
                            $m++;
                        }else{
                            $out[$m]=array('location'=>$last['latitude'].','.$last['longitude'],'stopover'=>true,'time'=>$last['ctime']);
//                            $out1[$m] = array('latitude'=>$last['latitude'],'longitude'=>$last['longitude'],'content'=>$content);

                            $last = $last;
                        }

                        if($ds > 0.004){
//                            $out[$m]=array('location'=>$values['latitude'].','.$values['longitude'],'stopover'=>true);
                            $out1[$m2] = array('latitude'=>$last2['latitude'],'longitude'=>$last2['longitude'],'content'=>'标记时间：'.date("Y-m-d H:i:s", $last2['ctime']).'<br />'.$content);
                            $out2[$m2] = $last2['longitude'].','.$last2['latitude'];

                            $last2 = $values;
                            $content = '';
                            $m2++;
                        }else{
//                            $out[$m]=array('location'=>$last['latitude'].','.$last['longitude'],'stopover'=>true);
                            $out1[$m2] = array('latitude'=>$last2['latitude'],'longitude'=>$last2['longitude'],'content'=>'标记时间：'.date("Y-m-d H:i:s", $last2['ctime']).'<br />'.$content);
                            $out2[$m2] = $last2['longitude'].','.$last2['latitude'];

                            $last2 = $last2;
                        }
                    }else{
                        $last=$values;
                        $last2=$values;
                    }


                    if($m==0){
                        $outstart = array('location'=>$values['latitude'].','.$values['longitude']);
                        $outmid = array('latitude'=>$values['latitude'],'longitude'=>$values['longitude']);
                    }

                    $outend = array('location'=>$values['latitude'].','.$values['longitude']);

                }
/*
                $out1_new = array();
                if(!empty($out1)){
//                    $c_out = count($out);
                    $out1_tmp = array();
                    foreach($out1 as $out1_one){
                        if(empty($out1_tmp)){
                            $out1_tmp = $out1[0];
                            $out1_new[]=array('location'=>$out1[0]['latitude'].','.$out1[0]['longitude'],'stopover'=>true);
                        }
                        if(($out1_one['time']-$out1_tmp['time'])>1800){
                            $out1_tmp = $out1_one;
                            $out1_new[]=array('location'=>$out1_tmp['latitude'].','.$out1_tmp['longitude'],'content'=>$out1_tmp['content']);
                        }
                    }
                }
*/
                //轨迹最少间隔为两小时
                $out_new = array();
                if(!empty($out)){
//                    $c_out = count($out);
                    $out_tmp = array();
                    foreach($out as $out_one){
                        if(empty($out_tmp)){
                            $out_tmp = $out_one;
                            $out_new[]=array('location'=>$out_tmp['location'],'stopover'=>true);
                        }
                        if(($out_one['time']-$out_tmp['time'])>2){
                            $out_tmp = $out_one;
                            $out_new[]=array('location'=>$out_tmp['location'],'stopover'=>true);
                        }
                    }
                }

//                $out = array_slice($out, 0, 8);

                echo json_encode(
                    array(
                        'out'=>isset($out_new) ? $out_new : '',
                        'out1'=>isset($out1) ? $out1 : '',
                        'out2'=>isset($out2) ? implode(';',$out2) : '',
                        'outmid'=>isset($outmid) ? $outmid: '',
                        'outstart'=>isset($outstart) ? $outstart : '',
                        'outend'=>isset($outend) ? $outend : '',
                        'outshop'=>isset($outshop) ? $outshop : '',
                        'speed'=>isset($speed) ? $speed :''
                    )
                );
            }
        }


    }


    function get_point_distance($a_x, $a_y, $b_x, $b_y){
        $c = sqrt(($a_x-$b_x)*($a_x-$b_x) + ($a_y-$b_y)*($a_y-$b_y));
        return $c;
    }

    /**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Imgs;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Imgs']))
		{
			$this->imei_session();
			$user_id = Yii::app()->user->id;
			$model->attributes=$_POST['Imgs'];
			
            $img_root = Yii::app()->getBasePath().DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
//            $model->cid=0;
            $model->type=empty($model->type) ? 0 : intval($model->type);
            $model->order=0;
            $model->enabled=1;

            $model->uid = $user_id;
            $time =time();
            $model->ctime = $time;
            $model->utime = $time;

            $img = CUploadedFile::getInstance($model, 'img');
            if(!empty($img)){
                if(!is_dir($img_root.$user_id.DIRECTORY_SEPARATOR)){
                    mkdir($img_root.$user_id.DIRECTORY_SEPARATOR,0777,true);
                }
                $img_name  = md5(rand(1,100).date('YmdHis').rand(1,1000)).'.'.$img->extensionName;
                if (is_object($img)) {
                    $img->saveAs($img_root.$user_id.DIRECTORY_SEPARATOR.$img_name);
                    $model->img='/images/temp/'.$user_id.'/'.$img_name;
                }
            }else{
                $model->img='';
            }

            if($model->save()){
            	if ($_POST['Imgs']['title'] == '图片' && $_POST['Imgs']['cid'] > 0){
					$user = User::model()->findByPk($user_id);
					$phoneContent =array('img'=>'/images/temp/'.$user_id.'/'.$img_name,
							     'content'=>$_POST['Imgs']['content'],
							     'time'=>time(),
							     'cid'=>$_POST['Imgs']['cid'],
							     'longitude'=>$_POST['Imgs']['longitude'] ? $_POST['Imgs']['longitude'] : 0,
							     'latitude'=>$_POST['Imgs']['latitude'] ? $_POST['Imgs']['latitude'] : 0,
							     'user_name'=>$user->username,
					);
					$phoneContent = base64_encode(json_encode($phoneContent));
					$url = "http://eip.7sef.com/api/shopphone/index/data/".$phoneContent;
					$api = file_get_contents($url);
				}
                pd(json_encode(array('right'=>get_menu(-1))));
            }else{
                pd(json_encode(array('error'=>$model->errors)));
            }
		}

		$this->render('create',array(
			'model'=>$model,
			'data'=>base64_encode(json_encode($data))
		));
	}

    public function filterUpdateOwn($filterChain)
    {
        $id = Yii::app()->request->getParam('id', 0);
        $imgs=$this->loadModel($id);

        // Remove the 'rights' filter if the user is updating an own post
        // and has the permission to do so.
        if(Yii::app()->user->checkAccess('ImgsUpdateOwn', array('userid'=>$imgs->uid)))
            $filterChain->removeAt(1);

        $filterChain->run();
    }

    public function filterDeleteOwn($filterChain)
    {
        $id = Yii::app()->request->getParam('id', 0);
        $imgs=$this->loadModel($id);

        // Remove the 'rights' filter if the user is updating an own post
        // and has the permission to do so.
        if(Yii::app()->user->checkAccess('ImgsDeleteOwn', array('userid'=>$imgs->uid)))
            $filterChain->removeAt(1);

        $filterChain->run();
    }

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
        $img_temp = $model->img;
        $user_id = Yii::app()->user->id;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Imgs']))
		{
            $user_model = new UserLogin;
            $user_model->attributes=$_POST['UserLogin'];
            if($user_model->validate()) {
                $user_id = Yii::app()->user->id;
            }
            if(!empty($user_model->errors)){
                pd(json_encode(array('error'=>$user_model->errors)));
            }
            if($model->uid != $user_id){
                pd(json_encode(array('error'=>array('username'=>'当前用户没有权限'))));
            }


			$model->attributes=$_POST['Imgs'];
            if(empty($model->img)){
                $model->img = $img_temp;
            }

//            $model->uid = $user_id;
            $time =time();
            $model->utime = $time;

            $img_root = Yii::app()->getBasePath().DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
            $model->cid=0;
            $model->type=0;
            $model->order=0;
            $model->enabled=1;

            $img = CUploadedFile::getInstance($model, 'img');
            if(!empty($img)){
                if(!is_dir($img_root.$user_id.DIRECTORY_SEPARATOR)){
                    mkdir($img_root.$user_id.DIRECTORY_SEPARATOR,0777,true);
                }
                $img_name  = md5(rand(1,100).date('YmdHis').rand(1,1000)).'.'.$img->extensionName;
                if (is_object($img)) {
                    $img->saveAs($img_root.$user_id.DIRECTORY_SEPARATOR.$img_name);
                    $model->img='/images/temp/'.$user_id.'/'.$img_name;
                }
            }

//			if($model->save())
//				$this->redirect(array('view','id'=>$model->aid));
            if($model->save()){
                pd(json_encode(array('right'=>$model->attributes)));
            }else{
                pd(json_encode(array('error'=>$model->errors)));
            }
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Imgs');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Imgs('search');
		$model->unsetAttributes();  // clear any default values
        $model->uid = Yii::app()->user->id;
		if(isset($_GET['Imgs']))
			$model->attributes=$_GET['Imgs'];

		$this->render('admin',array(
			'model'=>$model,
            's'=>$model->search(),
		));
	}

    public function actionList_imgs()
    {
        $model=new Imgs('search_imgs');
        $model->unsetAttributes();  // clear any default values
//        $model->uid = Yii::app()->user->id;
        if(isset($_GET['Imgs']))
            $model->attributes=$_GET['Imgs'];

        $this->render('imgs',array(
            'model'=>$model,
            's'=>$model->search_imgs(),
        ));
    }

    public function actionList_post()
    {
        $model=new Imgs('search_post');
        $model->unsetAttributes();  // clear any default values
//        $model->uid = Yii::app()->user->id;
        if(isset($_GET['Imgs']))
            $model->attributes=$_GET['Imgs'];

        $this->render('post',array(
            'model'=>$model,
            's'=>$model->search_post(),
        ));
    }

    public function actionList_place()
    {
        $model=new Imgs('search_place');
        $model->unsetAttributes();  // clear any default values
//        $model->uid = Yii::app()->user->id;
        if(isset($_GET['Imgs']))
            $model->attributes=$_GET['Imgs'];

        $this->render('place',array(
            'model'=>$model,
            's'=>$model->search_place(),
        ));
    }

    public function actionList_imei()
    {
        $model=new Imgs('search_place');
        $model->unsetAttributes();  // clear any default values
//        $model->uid = Yii::app()->user->id;
        if(isset($_GET['Imgs']))
            $model->attributes=$_GET['Imgs'];

        $this->render('admin',array(
            'model'=>$model,
            's'=>$model->search_imei(),
        ));
    }

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Imgs the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Imgs::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Imgs $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='imgs-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	
}
